package com.cn.fw4j.mvc.page.impl;

import java.io.IOException;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.fw4j.mvc.page.inter.IPageTemplate;
import com.cn.fw4j.util.request.parameter.OutParam;

public class JspTemplate implements IPageTemplate {

	@Override
	public void Template(String path, OutParam outparam,
			HttpServletRequest request, HttpServletResponse response) {
		if(outparam != null && outparam.size()>0){
			Set<Object> keys = outparam.keySet();
			for(Object key : keys){
				Object value = outparam.get(key);
				if(value instanceof Cookie){
					response.addCookie((Cookie)value);
				}else{
					request.setAttribute(key.toString(), outparam.get(key));
				}
			}
		}
		
		if(path.startsWith("request:")){
			String forward = path.replace("request:","");
			if(!forward.startsWith(basePath(request))){
				forward = basePath(request) + forward;
			}
			RequestDispatcher rd = request.getRequestDispatcher(forward);
			try{
				rd.forward(request, response);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}else if(path.startsWith("redirect:")){
			try {
				String redirect = path.replace("redirect:", "");
				if(!redirect.startsWith("http://") && !redirect.startsWith(basePath(request))){
					redirect = basePath(request) + redirect;
				}
				response.sendRedirect(redirect);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
	}
	/**
	 * a String specifying the portion of the request URI that indicates the context of the request
	 * @param request
	 * @return String
	 */
	private String basePath(HttpServletRequest request){
		return request.getContextPath();
    }

}
